/**
 * Created by Pyj on 2019/08/20.
 */
/***********************面板-start****************************/
var rowData=[];

//角色主列表参数面板
var roleGridOpt={
    id:"roleGrid",//渲染对象ID 控件的唯一标识
    //title:"测试wdfGrid",//表格标题名暂时不要使用该属性,因为该实现为完善
    width:width,//表格宽度
    autoWidth:true,//是否自适应宽度,该属性设置时,列的width属性将失效,要让列的width属性生效请关闭该属性并设置colFixed属性为true
    autoHeight:true,//自动高度
    //colFixed:true,//固定列宽,该属性启动时列width属性有效,autoWidth属性无效
    className:"test",//表格样式类名
    //checkbox:true,//是否显示选中按钮
    isMulitCheck:true,//是否支持多选
    loadMsg:"正在加载数据请稍等",//表格加载显示信息
    rowData:rowData,
    root:"data",//服务端返回的数据对象名
    url:basePath+"/role/listByCondition",
    ////delayLoad:500,//在表格元素填充后延迟表格数据加载，单位毫秒
    columns:[
        {
            hidden : false,// 是否隐藏该列
            label : "名称",// 显示列名称
            name : "name",// 列字段属性名
            width : "100",// 列宽度
            isOrder : true// 是否排序
        },
        {
            hidden : false,// 是否隐藏该列
            label : "类型",// 显示列名称
            name : "type",// 列字段属性名
            width : "50",// 列宽度
            isOrder : true,// 是否排序
            formatter : function(columnValue) {
                // 格式化
                return FormatUtil.getRoleType(columnValue);
            }
        },
        {
            hidden : false,// 是否隐藏该列
            label : "状态",// 显示列名称
            name : "status",// 列字段属性名
            width : "50",// 列宽度
            isOrder : true,// 是否排序
            formatter : function(columnValue) {
                if(columnValue == 1) {
                    return "启用";
                } else {
                    return "禁用";
                }
            }
        },
        {
            hidden : false,// 是否隐藏该列
            label : "备注",// 显示列名称
            name : "description",// 列字段属性名
            width : "150",// 列宽度
            isOrder : true// 是否排序
        },
        {
            hidden : false,// 是否隐藏该列
            label : "操作",// 显示列名称
            name : "status",// 列字段属性名`
            width : "120",// 列宽度
            isOrder : true,// 是否排序
            isFmtHtml:true,//格式化是否返回html
            formatter : function(columnValue,rowData){

                var menus="<a class='gridview_btn' href=\"javascript:editRoleMenus('"+rowData.id+"','"+rowData.name+"');\">菜单</a>";
                var permission="<a class='gridview_btn' href=\"javascript:editPermissions('"+rowData.id+"','"+rowData.name+"');\">权限</a>";
                return menus+permission;
            }
        }
    ],
    event:{
        readyLoad:function(opt,gridObj){//grid数据加载前执行
            $(".panel").css("display","none");
        },
        onRowMouse:function (rowData,gridObj) {
            var edit=$("<a class='gridedit_btn' href=\"javascript:editRole('"+rowData.id+"','"+rowData.name+"');\">修改</a>");
            return [edit];
        }
    }
};

//角色添加面板参数
var addRolePanelOpt={
    width:width,//高
    height:height,//宽
    bombType:BOMB_TYPE2,
    valForm:{
        valParam:[//验证参数
            {
                inputname:"role_name_AddPanel",
                isnull:true,
                isnullmsg:"名称不能为空",
                event:"blur"
            }
        ]
    },//验证
    action:basePath+"/role/save",//表单提交地址
    event:{
        onClosed:function(obj){
            $("#roleGrid").wdfGrid("reload",roleGridOpt);
        },
        submitSuccessed:function(data,panelObj){
            setTimeout(function(){
                panelObj.close();
                $("#roleGrid").wdfGrid("reload",roleGridOpt);
            },1000);
        }
    }
};

//角色编辑面板参数
var editRolePanelOpt={
    width:width,//高
    height:height,//宽
    bombType:BOMB_TYPE2,
    valForm:{
        valParam:[//验证参数
            {
                inputname:"role_name_EditPanel",
                isnull:true,
                isnullmsg:"名称不能为空",
                event:"blur"
            }
        ]
    },//验证
    action:basePath+"/role/update",//表单提交地址
    event:{
        onClosed:function(obj){
            $("#roleGrid").wdfGrid("reload",roleGridOpt);
        },
        submitSuccessed:function(data,panelObj){
            setTimeout(function(){
                panelObj.close();
                $("#roleGrid").wdfGrid("reload",roleGridOpt);
            },1000);
        }
    }
};

//角色菜单树参数
var roleTreeOpt={
    data : {
        simpleData : {
            enable : true
        }
    },
    check: {
        enable: true,
        chkStyle:"checkbox",
        chkboxType: { "Y": "p", "N": "s" }
    },
    callback : {
        //beforeDrag : beforeDrag,
        //beforeEditName : beforeEditName,
        //beforeRemove : beforeRemove,
        //beforeRename : beforeRename,
        //onRemove : onRemove,
        //onRename : onRename,
        //onClick : zTreeOnClick
    }
};

//角色权限树参数
var permissionTreeOpt={
    data : {
        simpleData : {
            enable : true
        }
    },
    check: {
        enable: true,
        chkStyle:"checkbox",
        chkboxType: { "Y": "s", "N": "ps" }
    },
    callback : {
        //beforeDrag : beforeDrag,
        //beforeEditName : beforeEditName,
        //beforeRemove : beforeRemove,
        //beforeRename : beforeRename,
        //onRemove : onRemove,
        //onRename : onRename,
        //onClick : zTreeOnClick
    }
};

//角色菜单面板参数
var roleMenusPanelOpt={
    id:"roleMenusPanel",
    width:width,
    height:height,
    bombType:BOMB_TYPE2,
    action:basePath+"/menu/listRoleMenu",
    ztreeOption :roleTreeOpt,
    treeDataRoot:"data",
    event:{
        ztreeDataFilter:function(nodes){
            for(var i=0;i<nodes.length;i++){
                delete nodes[i].url;
            }
            return nodes;
        },
        okBtnClick:function(eventObj,panel){
            var menuTree=$.fn.zTree.getZTreeObj(panel.find(".ztree").attr("id"));
            var checkNodes=menuTree.getCheckedNodes(true);
            var menusStr="";
            var role=roleMenusPanel.data("editRoleData");
            if(checkNodes){
                $(checkNodes).each(function(i,obj){
                    if(i+1==checkNodes.length){
                        menusStr+=obj.id;
                        return;
                    }
                    menusStr+=obj.id+",";
                });
            }
            $.wdfProgress.progress("请稍等...",$("body"));
            $.ajax({
                url:basePath+"/role/updateMenu",
                data:{
                    menuIDS:menusStr,
                    id:role.id,
                    cType:"PCWEB"
                },
                dataType:"json",
                type: "post",
                contentType:"application/x-www-form-urlencoded",
                beforeSend:null,
                success:function(data){
                    if(data.status==1){
                        role.menuIDS=menusStr;
                        $.wdfProgress.showMsg(data.msg,$("body"),true);
                        setTimeout(function(){
                            $("#roleMenusPanel").find(".closeBtn").click();
                            $.wdfProgress.progRemove($("body"));
                            roleGridOpt.keepPage=true;
                            $("#roleGrid").wdfGrid("reload",roleGridOpt);
                            roleGridOpt.keepPage=false;
                        },1000);
                    }else{
                        $.wdfProgress.showMsg(data.msg,$("body"),true);
                    }
                },
                error:function (XMLHttpRequest, textStatus, errorThrown) {
                    $.wdfProgress.showMsg("系统错误或网络延迟！",$("body"),true);
                }
            });
        },
        resetBtnClick:function(eventObj,panel){

        }
    }
};

//角色权限面板参数
var rolePermissionPanelOpt={

    id:"rolePermissionPanel",
    width:width,
    height:height,
    bombType:BOMB_TYPE2,
    action:basePath+"/permission/listPermissionMenu",
    ztreeOption :permissionTreeOpt,
    treeDataRoot:"data",
    event:{
        ztreeDataFilter:function(nodes){
            for(var i=0;i<nodes.length;i++){
                delete nodes[i].url;
            }
            return nodes;
        },
        okBtnClick:function(eventObj,panel){
            var permissionTree=$.fn.zTree.getZTreeObj(panel.find(".ztree").attr("id"));
            var checkNodes=permissionTree.getCheckedNodes(true);
            var persStr="";
            var role=rolePermissionPanel.data("editPermissionData");
            if(checkNodes){
                $(checkNodes).each(function(i,obj){
                    if(i+1==checkNodes.length){
                        persStr+=obj.id;
                        return;
                    }
                    persStr+=obj.id+",";
                });
            }
            $.wdfProgress.progress("请稍等...",$("body"));
            $.ajax({
                url:basePath+"/role/updatePermisson",
                data:{
                    permissionIDS:persStr,
                    id:role.id,
                    cType:"PCWEB"
                },
                dataType:"json",
                type: "post",
                contentType:"application/x-www-form-urlencoded",
                beforeSend:null,
                success:function(data){
                    if(data.status==1){
                        role.permissionIDS=persStr;
                        $.wdfProgress.showMsg(data.msg,$("body"),true);
                        setTimeout(function(){
                            $("#rolePermissionPanel").find(".closeBtn").click();
                            $.wdfProgress.progRemove($("body"));
                            roleGridOpt.keepPage=true;
                            $("#roleGrid").wdfGrid("reload",roleGridOpt);
                            roleGridOpt.keepPage=false;
                        },1000);
                    }else{
                        $.wdfProgress.showMsg(data.msg,$("body"),true);
                    }
                },
                error:function (XMLHttpRequest, textStatus, errorThrown) {
                    $.wdfProgress.showMsg("系统错误或网络延迟！",$("body"),true);
                }
            });
        },
        resetBtnClick:function(eventObj,panel){

        }
    }
};

/***********************面板-end****************************/

/***********************通用下拉列表-start****************************/
//角色管理-查询类型
var role_type_SearchPanel_SelOpt={
    id:"role_type_SearchPanel",          //渲染对象ID
    name:"types",
    className:"wdfSel",          //样式名称
    zTreeOption:"default",       //zTree配置参数
    mulitValsChecked:true,       //是否为多值选择模式
    width:300,                   //下拉面板的宽度
    height:200,                  //下拉面板高度
    zIndex:9999,                 //下面板层层级
    root:"data",                 //请求服务端返回的json对象的数据字段名称
    searchBar:{                  //搜索栏定义
        isOpen:true,                 //是否开启
        title:""                     //标题
    },
    data:[
        {
            id:1,
            name:"系统角色"
        },
        {
            id:2,
            name:"项目角色"
        }
    ],                     //要绑定到控件的数据，如果有该参数，则不会触发向服务端请求数据
    isFixedHeight:true,          //是否固定下拉面板高度
    param:{//要提交的参数

    },
    dataFilter:function(nodes){  //如果非异步模式的树控件数据过滤操作

    },
    event:{
        onZTreeLoaded:function(zTree,selObj){
            // selObj.wdfSel("setVal","");
        },
        onChange:function(inputObj,selObj){

        },
        onNodeClick:function(nodeObj){
            return true;
        }
    }
};

/***********************通用下拉列表-end****************************/

/***********************业务操作-start****************************/
//角色添加
function addRole(){
    addRolePanel.find("#addRoleForm")[0].reset();
    addRolePanel.show("新增角色");
    addRolePanel.find(".wdfValidate_Msg").remove();
    addRolePanel.find("input").css('borderColor',"");
    addRolePanel.find("select").css('borderColor',"");
    addRolePanel.find("textarea").css('borderColor',"");
}

//角色编辑
function editRole(id,name){
    var rowDatas=$("#roleGrid").wdfGrid("getRowDatasByDK",{key:"id",value:id});
    var role=rowDatas[0];
    editRolePanel.find("#role_id_EditPanel").val(role.id);
    editRolePanel.find("#role_name_EditPanel").val(role.name);
    editRolePanel.find("#role_type_EditPanel").val(role.type);
    editRolePanel.find("#role_status_EditPanel").val(role.status);
    editRolePanel.find("#role_description_EditPanel").val(role.description);
    editRolePanel.find(".error").removeClass("error");
    editRolePanel.find(".msgBar").remove();
    editRolePanel.show("修改角色"+"("+name+")");
}

//角色菜单更新
function editRoleMenus(id,name){
    var rowData=$("#roleGrid").wdfGrid("getRowDatasByDK",{key:"id",value:id})[0];
    roleMenusPanel.data("editRoleData",rowData);
    roleMenusPanel.show("("+name+")角色菜单",false);
    var menuTree=$.fn.zTree.getZTreeObj(roleMenusPanel.find(".ztree").attr("id"));
    menuTree.checkAllNodes(false);
    menuTree.expandAll(true);
    var menusArray=[];

    $.ajax({
        url:basePath+"/role/get",
        data:{
            id:id
        },
        async:false,
        dataType:"json",
        type: "post",
        contentType:"application/x-www-form-urlencoded",
        beforeSend:null,
        success:function(data){
            rowData.menus = data.data.menus;

        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            $.wdfProgress.showMsg("系统错误或网络延迟！",$("body"),true);
        }
    });
    if(rowData.menus!=null){
        if(rowData.menus.length>0){
            $(rowData.menus).each(function () {
                menusArray.push(this.id);
            });
        }else{
            //menusArray.push(rowData.menus[0].id);
        }
    }
    for (var i=0;i<menusArray.length;i++) {
        var checkNode=menuTree.getNodeByParam("id",menusArray[i], null);
        menuTree.checkNode(checkNode,true,true);
    }
}

//角色权限更新
function editPermissions(id,name){
    var rowData=$("#roleGrid").wdfGrid("getRowDatasByDK",{key:"id",value:id})[0];
    rolePermissionPanel.data("editPermissionData",rowData);
    rolePermissionPanel.show("("+name+")角色权限",false);
    var permissionTree=$.fn.zTree.getZTreeObj(rolePermissionPanel.find(".ztree").attr("id"));
    permissionTree.checkAllNodes(false);
    permissionTree.expandAll(true);
    var permissionArray=[];

    $.ajax({
        url:basePath+"/role/get",
        data:{
            id:id
        },
        async:false,
        dataType:"json",
        type: "post",
        contentType:"application/x-www-form-urlencoded",
        beforeSend:null,
        success:function(data){
            rowData.permissions = data.data.permissions;

        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            $.wdfProgress.showMsg("系统错误或网络延迟！",$("body"),true);
        }
    });
    if(rowData.permissions!=null){
        if(rowData.permissions.length>0){
            $(rowData.permissions).each(function () {
                permissionArray.push(this.id);
            });
        }else{
            //permissionArray.push(rowData.permissions[0].id);
        }
    }
    for (var i=0;i<permissionArray.length;i++) {
        var checkNode=permissionTree.getNodeByParam("id",permissionArray[i], null);
        permissionTree.checkNode(checkNode,true,true);
    }
}

//验证消息显示
function showMsg(msg,input,obj){
    var msgBar=$("<div  class='msgBar'>"+msg+"</div>");
    $(".msgBar").remove();
    obj.append(msgBar);
    msgBar.animate({"opacity":1},500);
    $(input).data("showMsg",msgBar);
    $(input).addClass("error");
};

//角色条件查询
function search(){
	roleGridOpt.param=$("#searchForm").serialize();
	$("#roleGrid").wdfGrid("reload",roleGridOpt);
}

//查询条件重置
function resetSearch(){
	$("#searchForm")[0].reset();
	$("#role_type_SearchPanel").wdfSel("setVal","");
    search();
}
/***********************业务操作-end****************************/

/***********************页面初始化-start****************************/
$(document).ready(function(){
	roleGridOpt.param=$("#searchForm").serialize();
	roleGridOpt.height = $(document).height() - $('#searchPanel').height()-20;
	$("#roleGrid").wdfGrid("init",roleGridOpt);

    addRolePanel=$("#addRolePanel").wdfPanel("FormPanel",addRolePanelOpt);
    editRolePanel=$("#editRolePanel").wdfPanel("FormPanel",editRolePanelOpt);
    roleMenusPanel=$("#roleMenusPanel").wdfPanel("TreePanel",roleMenusPanelOpt);
    rolePermissionPanel = $("#rolePermissionPanel").wdfPanel("TreePanel",rolePermissionPanelOpt);

    initSel(role_type_SearchPanel_SelOpt);
});
/***********************页面初始化-end****************************/
